import 'dart:io';

import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

class FileOperationRoute extends StatefulWidget {
  const FileOperationRoute({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _FileOperationRouteState();
}

class _FileOperationRouteState extends State<FileOperationRoute> {
  int _counter = 0;

  Future<File> _loadFile() async {
    var path = (await getApplicationDocumentsDirectory()).path;
    return File('$path/counter.txt');
  }

  Future<int> _readCounter() async {
    try {
      var file = await _loadFile();
      return int.parse(file.readAsStringSync());
    } on FileSystemException {
      return 0;
    }
  }

  void _incrementCounter() async {
    setState(() {
      _counter++;
    });
    (await _loadFile()).writeAsStringSync('$_counter');
  }

  @override
  void initState() {
    super.initState();
    _readCounter().then((value) {
      setState(() {
        _counter = value;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('File Operation'),
      ),
      body: Center(
        child: Text(
          '$_counter',
          style: Theme.of(context).textTheme.headline1,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add),
        onPressed: _incrementCounter,
      ),
    );
  }
}
